<!-- 用户编辑弹窗 -->
<template>
  <ele-modal width="680px"
             :visible="visible"
             :append-to-body="true"
             :close-on-click-modal="true"
             custom-class="ele-dialog-form"
             :title="isUpdate ? '修改用户' : '添加用户'"
             @update:visible="updateVisible">
    <el-form ref="form"
             :model="form"
             :rules="rules"
             label-width="82px">
      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { sm: 24 } : { span: 24 }">
          <el-form-item label="用户账号:"
                        prop="name">
            <el-input clearable
                      :maxlength="20"
                      :disabled="isUpdate"
                      v-model="form.name"
                      placeholder="请输入用户账号" />
          </el-form-item>

          <el-form-item label="真实姓名:"
                        prop="real_name">
            <el-input placeholder="请输入真实姓名"
                      v-model="form.real_name" />
          </el-form-item>
          <el-form-item label="手机号:"
                        prop="phone">
            <el-input clearable
                      :maxlength="11"
                      v-model="form.phone"
                      placeholder="请输入手机号" />
          </el-form-item>

          <el-form-item v-if="!isUpdate"
                        label="登录密码:"
                        prop="password">
            <el-input show-password
                      :maxlength="20"
                      v-model="form.password"
                      placeholder="请输入登录密码" />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { sm:12 } : { span: 12 }">
          <div class="">

            <div class="flexCenter"
                 v-for="(item,i) in form.roleIds"
                 :key="i">
              <el-form-item label="角色:">

                <role-select @isShowStore="e=>isShowStoreFn(e,i)"
                             v-model="form.roleIds[i]" />

              </el-form-item>

            </div>

          </div>
        </el-col>

      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary"
                 :loading="loading"
                 @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>
	
	<script>
import { phoneReg } from 'ele-admin';
import RoleSelect from './role-select.vue';
// import StoreSelect from './store-select.vue';
import { addUser, updateUser, checkExistence } from '@/api/system/user';

export default {
  components: { RoleSelect },
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  data () {
    const defaultForm = {
      id: null,
      name: '',
      real_name: '',
      roleIds: [],

      phone: '',
      password: '',
    };
    return {
      defaultForm,
      // 表单数据
      form: { ...defaultForm },
      // 表单验证规则
      rules: {
        username: [
          {
            required: true,
            trigger: 'blur',
            validator: (_rule, value, callback) => {
              if (this.isUpdate) {
                callback();
                return;
              }
              if (!value) {
                return callback(new Error('请输入用户账号'));
              }
              checkExistence('username', value, this.data?.name)
                .then(() => {
                  callback(new Error('账号已经存在'));
                })
                .catch(() => {
                  callback();
                });
            }
          }
        ],
        name: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        real_name: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],

        roleIds: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }
        ],

        password: [
          {
            required: true,
            pattern: /^[\S]{5,18}$/,
            message: '密码必须为6-18位非空白字符',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            pattern: phoneReg,
            message: '手机号格式不正确',
            trigger: 'blur'
          }
        ],

      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      isShowStore: true,
      isShowStoreIndex: 10000000000,
      isSelectStoreBol: false
    };
  },
  computed: {
    // 是否开启响应式布局
    styleResponsive () {
      return this.$store.state.theme.styleResponsive;
    }
  },
  methods: {
    isSelectFn (e) {
      this.isSelectStoreBol = e
    },
    isShowStoreFn (e, index) {
      this.isShowStore = e,
        console.log(e, index, 'isShowStoreFn')
      if (e) {
        this.isSelectStoreBol = false
      } else {
        this.isSelectStoreBol = true
      }
      this.isShowStoreIndex = index
      if (!this.isShowStore) {
        console.log(this.form.storeId)
        console.log(this.form.storeId)
        // this.form.storeId[index] = 0
        this.$set(this.form.storeId, index, '');
      } else {
        this.$set(this.form.storeId, index, '请选择门店');
      }
    },
    /* 保存编辑 */
    save () {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.loading = true;
        const data = {
          ...this.form,
       
     
        };
        const saveOrUpdate = this.isUpdate ? updateUser : addUser;
          saveOrUpdate(data)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });

      });
    },
    /* 更新visible */
    updateVisible (value) {
      this.$emit('update:visible', value);
    },
    //删除字幕
    subtract (index) {
      this.form.roleIds.splice(index, 1)
      this.form.storeId.splice(index, 1)

    },
    // 添加
    add () {
      let content = ''
      this.form.roleIds.push(content)
      this.form.storeId.push('请选择门店')

    },
  },
  watch: {
    visible (visible) {
      if (visible) {
        console.log(visible, this.data)
        if (this.data) {

          this.$util.assignObject(this.form, {
            ...this.data,

            roleIds: this.data.roles.map((d) => d.role_id),
        
            password: ''
          });
          console.log(this.data, 'data')
          this.isUpdate = true;
          this.data.roles.forEach()
        } else {
          this.isUpdate = false;
          let content = ''
          this.form.roleIds.push(content)
          this.form.storeId.push('请选择门店')
          console.log(this.form)
        }
      } else {

        this.form.roleIds.splice(0, 1)
        this.form.storeId.splice(0, 1)
        console.log(this.form)
        this.$refs.form.clearValidate();
        this.form = { ...this.defaultForm };
      }
    }
  }
};
	</script>
	<style scoped >
/deep/.el-button--medium {
  height: 37px;
}
.flexCenter {
  display: flex;
  justify-content: center;
  align-content: center;
}
</style>
	